import axios from 'axios'
import { message } from 'antd'

const defaultConf = {
    headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      transformRequest: (data, header) => {
        // change charset
        header['common']['Accept'] = 'application/json;charset=UTF-8'

        return data
      },
    timeout: 100000000
}

const _request = (params = {}, fn = () => {}) => {
    return axios({...defaultConf, ...params})
    .then(res => {

        const { result } = res.data
        // if (code === 401) {
        //     window.location.href = '/'
        //     return
        // }


        if (result === 'success') {
            fn(false)
            const results = JSON.stringify(res.data).toString()
            // 无网关设置
            return { "result": results, "status": "success" }

            // return res.data
        }

        if (result !== 'success') {
            return res.data
        }
    })
    .catch(error => {
        console.log(error)
        if (String(error).indexOf('200') === -1 && String(error).indexOf('401') > -1 | String(error).indexOf('417') > -1) {
            window.location.href = '/home/first-login'
            return error
        } else if (String(error).indexOf('403')) {
            return { result: null, status: 'success' }
        } else if (String(error).indexOf('Network Error')) {
            return { result: null, status: 'error' }
        }
        fn(false)
        message.error(String(error || '网络错误'))
        return error
    })

}

export default (params) => {
    const type = typeof params

    if (type === 'function') {
        params(true)
        return obj => _request(obj, params)
    }

    if (type === 'object' && type !== null) {
        return _request(params)
    }
}
